<script setup lang="ts">
import { onMounted, ref, computed, watch, onActivated } from "vue";
import { Api } from "../../assets/api/api";
import { useRouter, useRoute } from "vue-router";
import LoadComponent from "@/components/LoadComponent.vue";
import { showToast } from "vant";
import {useStoriesStore} from "@/stores/index"
import {storeToRefs }from 'pinia'

//背景颜色选择
const oldBgcIndex = ref(0);
const bgcIndex = ref(0);
const bgcList = ref([
  "#e6e0d0",
  "#f9f8f5",
  "#d4e7f2",
  "#e0b6c4",
  "#a6bc9c",
  "#010101",
]);

//背景颜色板消失隐藏
const bgcChange = ref(false);
//控制文章字体颜色
const controlColor = ref(["#2e343f", "#555"]);
const controlIndex = ref(0);
//文章字体大小控制板消失隐藏
const fontChange = ref(false);
//控制文章字体大小
const fontSizeChange = ref(16);
const lineHeigthChange = ref(26);
const marginBottomChange = ref(0);
const fbFlag = ref(false);
const fsFlag = ref(false);
//控制收藏样式
const collectionChange = ref(false);
//控制全部功能版/
const allChange = ref(false);
//主要数据
const mainData = ref([]);
//标题
const title = ref("");
//章节数据
const sectionData = ref([]);
//控制内容在第几章
const sectionIndexData = ref(0);
//控制书币不够提示窗
const enoughHintWindow = ref(false);
//控制提示登录窗
const loginFlag = ref(false);

//获取vip状态 pinia 相关操作
const {vip} = storeToRefs(useStoriesStore());

//vue3自带方法
const router = useRouter();
const route = useRoute();

//获取章节数据
const sectionDataGet = async () => {
  let id = route.params.id;
  let { data } = await Api.CatalogueUrl(id as any);
  sectionData.value = data.data.catalog;
  if (sectionData.value[0].leaf == false) {
    sectionData.value.splice(0, 1);
  }
  // 检测是否登录
  if (JSON.parse(localStorage.getItem("LoginStatus") as any)) {
    // 在检测是否是vip
    if (vip.value) {
      let id = sectionData.value[sectionIndexData.value].secId;
      mainDataGet(id);
    } else {
      //判断是否存在价格
      if (sectionData.value[sectionIndexData.value].price) {
        // 检测书币是否足够
        if (
          JSON.parse(localStorage.getItem("price") as any) >
          sectionData.value[sectionIndexData.value].price
        ) {
          // 扣减书币
          let price = JSON.parse(localStorage.getItem("price") as any);
          price = price - sectionData.value[sectionIndexData.value].price;
          localStorage.setItem("price", price);
          showToast("支付成功");
          let id = sectionData.value[sectionIndexData.value].secId;
          mainDataGet(id);
        } else {
          enoughHintWindow.value = true;
        }
      } else if (sectionData.value[sectionIndexData.value + 1].price) {
        // 检测书币是否足够
        if (
          JSON.parse(localStorage.getItem("price") as any) >
          sectionData.value[sectionIndexData.value + 1].price
        ) {
          // 扣减书币
          let price = JSON.parse(localStorage.getItem("price") as any);
          price = price - sectionData.value[(sectionIndexData.value = 1)].price;
          localStorage.setItem("price", price);
          showToast("支付成功");
          let id = sectionData.value[sectionIndexData.value].secId;
          mainDataGet(id);
        } else {
          enoughHintWindow.value = true;
        }
      }
    }
  } else {
    // 检测是否需要书币
    if (sectionData.value[sectionIndexData.value].price < 0) {
      let id = sectionData.value[sectionIndexData.value].secId;
      mainDataGet(id);
    } else {
      loginFlag.value = true;
    }
  }
};
//获取内容数据
const mainDataGet = async (id: String) => {
  let { data } = await Api.LookBookUrl(route.params.id as String, id);
  //进行数据处理
  let str = data.data.content;
  let reg = /(<span>)((\w|\W){0,})(<\Dspan>)/gm;
  let reg2 = /(<p>)((\w|\W){0,})(<\Dp>)/gm;
  let content1 = str.match(reg2);
  //截取所需数据
  let content2 = content1[0]
    .split("<br />")
    .join("")
    .split("<p>")
    .join("")
    .split("</p>");
  // 获取标题
  title.value = str.match(reg)[0].split("<span>").join("").split("</span>")[0];
  // 清除空数据
  let arr = [];
  for (let i = 0; i < content2.length; i++) {
    if (content2[i].trim() == "") {
      arr.unshift(i);
    }
  }
  for (let j = 0; j < arr.length; j++) {
    content2.splice(arr[j], 1);
  }
  //得到最终数据
  mainData.value = content2;
};
// 控制上下章节
const sectionDown = () => {
  mainData.value = [];
  if (sectionIndexData.value <= sectionData.value.length - 1) {
    // 通过获取第sectionIndexData.value个数组的id传参给主要数据获取小说内容
    // 当小说已是最后一章进行提示
    if (sectionIndexData.value == sectionData.value.length - 1) {
      sectionDataGet();
      showToast("已到最后一章");
    } else {
      sectionIndexData.value += 1;
      sectionDataGet();
      window.scroll({ top: 0 });
    }
  }
};
const sectionUp = () => {
  mainData.value = [];
  if (sectionIndexData.value >= 0) {
    // 通过获取第sectionIndexData.value个数组的id传参给主要数据获取小说内容
    // 当小说已是第一章进行提示
    if (sectionIndexData.value == 0) {
      sectionDataGet();
      showToast("已到第一章");
    } else {
      sectionIndexData.value = sectionIndexData.value - 1;
      sectionDataGet();
      window.scroll({ top: 0 });
    }
  }
};
// 背景颜色控制
const bfChange = () => {
  //变成夜晚模式
  if (controlIndex.value == 0) {
    controlIndex.value = 1;
    if (bgcIndex.value != 5) {
      oldBgcIndex.value = bgcIndex.value;
    }
    bgcIndex.value = 5;
  }
  //变成白天模式
  else {
    controlIndex.value = 0;
    bgcIndex.value = oldBgcIndex.value;
  }
};
//字体大小控制
const fsBig = () => {
  if (!fbFlag.value) {
    if (fontSizeChange.value <= 28) {
      fontSizeChange.value += 2;
      lineHeigthChange.value += 2;
      marginBottomChange.value += 1;
      fsFlag.value = false;
      if (fontSizeChange.value == 30) {
        showToast("已达到最大值");
        fbFlag.value = true;
      }
    }
  }
};
const fs_small = () => {
  if (fontSizeChange.value >= 18) {
    fontSizeChange.value -= 2;
    lineHeigthChange.value -= 2;
    marginBottomChange.value -= 1;
    fbFlag.value = false;
    if (fontSizeChange.value == 16) {
      showToast("已达到最小值");
      fsFlag.value = true;
    }
  }
};
//点击将功能隐藏
const allChangeFunctions = (e: any) => {
  if (
    e.target.className == "look_book" ||
    e.target.className == "title" ||
    e.target.localName == "p"
  ) {
    allChange.value = !allChange.value;
  }
};
//跳转目录页
const goCatalogue = () => {
  router.push({
    name: "catalogue",
    params: {
      id: route.params.id,
    },
  });
};

const fbSChange = computed(() => {
  return fontSizeChange.value == 30 ? true : false;
});
const fsSChange = computed(() => {
  return fontSizeChange.value == 16 ? true : false;
});
const load = computed(() => {
  return mainData.value.length == 0 ? true : false;
});

onMounted(() => {
  sectionDataGet();
  let num = route.query.contentIndexid;
  sectionIndexData.value = (num as any) * 1;
});

watch(sectionIndexData, (nv: Number, ov: Number) => {
  if (nv != ov) {
    let arr = JSON.parse(localStorage.getItem("novelChapter") as any);
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].id == route.params.id) {
        arr[i].index = sectionIndexData.value;
        localStorage.setItem("novelChapter", JSON.stringify(arr));
      }
    }
  }
});
</script>

<template>
  <div
    @click="allChangeFunctions($event)"
    class="look_book_view"
    :style="{ background: bgcList[bgcIndex] }"
  >
    <LoadComponent :load="load"></LoadComponent>
    <div v-if="mainData.length == 0 ? false : true" class="look_book_box">
      <!-- 顶部下拉 -->
      <div class="nav" v-if="allChange">
        <div class="img_box">
          <div class="img1" @click="router.push('/')"></div>
        </div>
        <div class="img_box">
          <div class="img2" :class="{ con: collectionChange }"></div>
        </div>
      </div>
      <!-- 主要内容 -->
      <div class="content">
        <h1
          class="title"
          :style="{
            color: controlColor[controlIndex],
            fontSize: fontSizeChange + 'px',
            lineHeight: lineHeigthChange + 'px',
            marginBottom: marginBottomChange + 'px',
          }"
        >
          {{ title }}
        </h1>
        <p
          :style="{
            color: controlColor[controlIndex],
            fontSize: fontSizeChange + 'px',
            lineHeight: lineHeigthChange + 'px',
          }"
          v-for="(item, index) in mainData"
          :key="index"
        >
          {{ item }}
        </p>
      </div>
      <!-- 左边跳转目录 -->
      <div class="catalogue" v-if="allChange" @click="goCatalogue">
        <div class="img_box"></div>
      </div>
      <!-- 底部上拉 -->
      <ul class="foot" v-if="allChange">
        <li class="li" @click="sectionUp">
          <div class="img"></div>
          <span>上一章</span>
        </li>
        <!-- 字体大小控制 -->
        <li class="li">
          <div class="img img2" @click="fontChange = !fontChange"></div>
          <span>字体</span>
          <!-- 控制字体变大变小 -->
          <div
            v-if="fontChange"
            class="font_size"
            @mouseleave="fontChange = false"
          >
            <div class="button">
              <div
                @click="fs_small"
                class="bimg1"
                :class="{ con: fsSChange }"
              ></div>
            </div>
            <div class="button">
              <div
                @click="fsBig"
                class="bimg2"
                :class="{ con: fbSChange }"
              ></div>
            </div>
          </div>
        </li>
        <!-- 夜间模式 -->
        <li class="li" @click="bfChange">
          <div class="img img3"></div>
          <span>{{ controlIndex == 0 ? "黑夜" : "白天" }}</span>
        </li>
        <!-- 背景颜色控制 -->
        <li class="li">
          <div class="img img4" @click="bgcChange = !bgcChange"></div>
          <span>背景</span>
          <ul
            class="background_color"
            v-if="bgcChange"
            @mouseleave="bgcChange = false"
          >
            <li>
              <div
                class="bgc1"
                :class="{ con: bgcIndex == 0 }"
                @click="bgcIndex = 0"
              ></div>
              <span>羊皮纸</span>
            </li>
            <li>
              <div
                class="bgc2"
                :class="{ con: bgcIndex == 1 }"
                @click="bgcIndex = 1"
              ></div>
              <span>淡雅白</span>
            </li>
            <li>
              <div
                class="bgc3"
                :class="{ con: bgcIndex == 2 }"
                @click="bgcIndex = 2"
              ></div>
              <span>冰霜蓝</span>
            </li>
            <li>
              <div
                class="bgc4"
                :class="{ con: bgcIndex == 3 }"
                @click="bgcIndex = 3"
              ></div>
              <span>浪漫粉</span>
            </li>
            <li>
              <div
                class="bgc5"
                :class="{ con: bgcIndex == 4 }"
                @click="bgcIndex = 4"
              ></div>
              <span>护眼绿</span>
            </li>
          </ul>
        </li>
        <li class="li" @click="sectionDown">
          <div class="img img5"></div>
          <span>下一章</span>
        </li>
      </ul>
    </div>
    <!-- 书币不够提示窗 -->
    <div class="enoughHintWindow" v-if="enoughHintWindow">
      <p>您的书币不够，请充值</p>
      <p>
        <button @click="router.go(-1)">取消</button>
        <button @click="router.push('/voucherCenter')">确定</button>
      </p>
    </div>
    <!-- 提示登录 -->
    <div class="enoughHintWindow" v-if="loginFlag">
      <p>此章节需要书币，请先登录</p>
      <p>
        <button @click="router.go(-1)">取消</button>
        <button @click="router.push('/login')">确定</button>
      </p>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.look_book {
  background-color: #fff;
  min-height: 100vmax;
  z-index: -1;
}
.title {
  font-size: 16px;
  height: 27px;
  line-height: 27px;
  font-weight: bold;
  word-wrap: break-word;
  word-break: break-all;
  color: #2e343f;
  text-align: center;
}
.content {
  padding: 10px;
  padding-bottom: 0;
  h1 {
    font-size: 16px;
    color: #2e343f;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  p {
    line-height: 26px;
    color: #2e343f;
    text-indent: 2em;
    word-wrap: break-word;
    word-break: break-all;
  }
}
.nav {
  display: flex;
  position: fixed;
  width: 100%;
  z-index: 999;
  top: 0;
  left: 0;
  height: 44px;
  background-color: #444952;
  justify-content: space-between;
  align-items: center;
  .img_box {
    width: 26px;
    height: 26px;
    overflow: hidden;
    margin: 0 14px;
    .img1 {
      width: 26px;
      height: 46px;
      background: url("/public/img/home/LookBookIndex2.png") no-repeat 2px -1px;
      background-size: cover;
    }
    .img2 {
      width: 24px;
      height: 46px;
      background: url("/public/img/home/LookBookIndex2.png") no-repeat -24px -1px;
      background-size: cover;
      &.con {
        background: url("/public/img/home/LookBookIndex2.png") no-repeat -47px -1px;
        background-size: cover;
      }
    }
  }
}
.catalogue {
  position: fixed;
  top: 50%;
  transform: translateY(-50%);
  width: 54px;
  height: 54px;
  border-radius: 50%;
  background-color: #4d5459;
  left: -19px;
  z-index: 999;
  .img_box {
    top: 19px;
    left: 25px;
    width: 21px;
    height: 17px;
    content: "";
    display: block;
    position: relative;
    background-size: 21px 34px;
    background-image: url("/public/img/home/ml.png");
  }
}
.foot {
  display: flex;
  width: 100%;
  height: 44px;
  position: fixed;
  background-color: #4d5459;
  bottom: 0;
  z-index: 999;
  .li {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 4px 0;
    width: 82px;
    position: relative;
    &:hover {
      background-color: #292b2e;
    }
    span {
      font-size: 12px;
      color: #fff;
    }
    .img {
      width: 21px;
      height: 20px;
      background-position-y: -20px;
      background-size: 105px 60px;
      background-image: url("/public/img/home/LookBookIndex.png");
    }
    .img2 {
      background-position-x: -21px;
    }
    .img3 {
      background-position-x: -42px;
    }
    .img4 {
      background-position-x: -63px;
    }
    .img5 {
      background-position-x: -84px;
    }
  }
  .font_size {
    position: absolute;
    display: flex;
    padding: 15px;
    background-color: #8e949d;
    border: 1px solid #656b74;
    border-radius: 3px;
    top: -78px;
    left: -55px;
    &::before {
      top: 100%;
      left: 77px;
      z-index: 2;
      content: "";
      display: block;
      position: absolute;
      border-style: solid;
      border-width: 12px 12px 0;
      border-color: #8e949d transparent;
    }
    .button {
      width: 130px;
      height: 34px;
      background-color: #f2f2f2;
      margin-right: 10px;
      display: flex;
      justify-content: center;
      align-items: center;
      &:nth-of-type(2) {
        margin-right: 0;
      }
    }
    .bimg1 {
      width: 27px;
      height: 20px;
      background-size: 108px 40px;
      background-position-x: 0px;
      background-image: url("/public/img/home/fs.png");
      &.con {
        background-position-x: -54px;
      }
    }
    .bimg2 {
      width: 27px;
      height: 20px;
      background-size: 108px 40px;
      background-position-y: -20px;
      background-image: url("/public/img/home/fs.png");
      &.con {
        background-position-x: -54px;
      }
    }
  }
  .background_color {
    position: absolute;
    width: 266px;
    height: 61px;
    background-color: #8e949d;
    border-radius: 3px;
    border: 1px solid #656b74;
    display: flex;
    justify-content: space-between;
    top: -89px;
    right: -56px;
    padding: 8px 13px;
    &::before {
      top: 100%;
      left: 188px;
      z-index: 2;
      content: "";
      position: absolute;
      border-style: solid;
      border-width: 12px 12px 0;
      border-color: #8e949d transparent;
    }
    li {
      div {
        width: 39px;
        height: 39px;
        padding: 2px;
        border: 1px solid #ffffff;
        border-radius: 1px;
        &.con {
          padding: 0;
          border: 3px solid #ff6000;
          border-radius: 3px;
        }
      }
    }
    .bgc1 {
      background-color: #e6e0d0;
    }
    .bgc2 {
      background-color: #f9f8f5;
    }
    .bgc3 {
      background-color: #d4e7f2;
    }
    .bgc4 {
      background-color: #e0b6c4;
    }
    .bgc5 {
      background-color: #a6bc9c;
    }
  }
}
.down_load {
  height: 100px;
  line-height: 100px;
  text-align: center;
  font-size: 16px;
  color: #998c7f;
}
.enoughHintWindow {
  width: 300px;
  height: 100px;
  background-color: #f3f3f3;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border-radius: 3px;
  p {
    font-size: 14px;
    text-align: center;
    margin-top: 15px;
    button {
      margin-right: 10px;
      width: 80px;
      height: 30px;
      border-radius: 3px;
      border: 1px solid #dedede;
      background-color: #f54b41;
      color: #fff;
    }
  }
}
</style>